package cn.edu.sziit.bbs.controller;

import cn.edu.sziit.bbs.model.Post;
import cn.edu.sziit.bbs.model.User;

import cn.edu.sziit.bbs.service.PostService;
import cn.edu.sziit.bbs.service.UserService;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//content.jsp
@Controller
public class ContentController {

    @Autowired
    private PostService postService;
    @Autowired
    private UserService userService;

    /**
     * content.jsp页面显示的帖子
     *
     * @param number
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/content", method = RequestMethod.GET)
    public Map<String, String> indexShow(Integer number, HttpSession session) {
        Map<String, String> map = new HashMap<>();

        List<Post> postsAll = postService.selectAll();
        List<Post> posts = null;

        if (number <= 0) {
            map.put("info", "页数有误");
            return map;
        }

        if (postsAll.size() >= 6 * number) {
            posts = postsAll.subList(6 * (number - 1), 6 * number);

        } else if (postsAll.size() >= 6 * (number - 1) && postsAll.size() < 6 * number) {
            posts = postsAll.subList(6 * (number - 1), postsAll.size());
        } else {
            map.put("info", "页数有误");
            return map;
        }

        System.out.println(posts.size());
        session.setAttribute("posts", posts);
        session.setAttribute("page", number);

        map.put("info", "success");

        return map;
    }

    @RequestMapping(value = "/getUsers", method = RequestMethod.GET)
    public String getUsers(HttpSession session) {
        List<User> users = userService.selectAll();
        session.setAttribute("users", users);
        return "admin/usersShow";
    }

    @ResponseBody
    @RequestMapping(value = "/userDelete", method = RequestMethod.GET)
    public String userDelete(Integer userId) {

        userService.deleteByPrimaryKey(userId);

        return "删除用户成功";
    }

    @RequestMapping(value = "/getPosts", method = RequestMethod.GET)
    public String getPosts(HttpSession session) {
        List<Post> adminPosts = postService.selectAll();
        session.setAttribute("adminPosts", adminPosts);
        return "admin/postsShow";
    }

}
